<template>
  <div class="mt-2">
    <van-list
      @load="loadData"
      :loading="loading"
      :finished-text="'没有更多了'"
      :finished="finished"
    >
      <OrderItem v-for="item in orderList" :key="item.id" :item="item" @ok="loadData()" />
    </van-list>
  </div>
</template>

<script setup lang="ts">
import OrderItem from './OrderItem.vue'
import { getOrderApi } from '@/apis/collection'
import { showNotify } from 'vant'
import { onMounted, onUnmounted, ref, watch } from 'vue'

const props = defineProps({
  orderStatus: {
    type: Number,
    default: 0
  },
  search: {
    type: Object,
    default: () => ({})
  }
})

const orderList = ref([])
const page = ref(1)
const pageSize = ref(10)
const loading = ref(false)
const finished = ref(false)
let timer = 0

function loadData() {
  loading.value = true
  getOrderApi({
    page: page.value,
    pageSize: pageSize.value,
    orderStatus: props.orderStatus,
    ...props.search
  })
    .then((res) => {
      const { list } = res
      if (list.length > 0) {
        orderList.value = [...orderList.value, ...list]
        page.value++
      } else {
        finished.value = true
      }
    })
    .finally(() => {
      loading.value = false
    })
}

function searchData(orderNo: string) {
  loading.value = true
  getOrderApi({
    page: 1,
    pageSize: 100,
    orderNo: orderNo
  })
    .then((res) => {
      const { list } = res
      if (list.length > 0) {
        orderList.value = list
        finished.value = true
      } else {
        showNotify('没有找到该订单')
      }
    })
    .finally(() => {
      loading.value = false
    })
}

watch(
  () => props.orderStatus,
  () => {
    orderList.value = []
    page.value = 1
    finished.value = false
    loadData()
  }
)

watch(
  () => props.search.dateTime,
  () => {
    orderList.value = []
    page.value = 1
    finished.value = false
    loadData()
  }
)

watch(
  () => props.search.search,
  () => {
    orderList.value = []
    page.value = 1
    finished.value = false
    loadData()
  }
)

function refreshList() {
  timer = setTimeout(() => {
    loadData()
    refreshList()
  }, 15000)
}

onMounted(() => {
  loadData()
  refreshList()
})

onUnmounted(() => {
  clearTimeout(timer)
})

defineExpose({
  loadData,
  searchData
})
</script>
